package cn.caixiong.org.controller;

import cn.caixiong.basic.utils.JsonResult;
import cn.caixiong.basic.utils.PageList;
import cn.caixiong.org.domain.Department;
import cn.caixiong.org.query.BaseQuery;
import cn.caixiong.org.service.IDepartmentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/dept")
public class DepartmentController {
    //注入依赖
    @Autowired
    private IDepartmentService departmentService;

    //查询所有
    @GetMapping
    public JsonResult findAll() {
        List<Department> list = departmentService.findAll();
        return JsonResult.createSuccess(list);
    }
    //查询级联
    @GetMapping("/treeList")
    public JsonResult treeList() {
        List<Department> list = departmentService.treeList();
        return JsonResult.createSuccess(list);
    }

    //分页
    @PostMapping("/findPage")
    public PageList<Department> findPage(@RequestBody BaseQuery query) {
        return departmentService.findPage(query);
    }

    @PostMapping("/parentDept")
    public JsonResult parentDept() {
        return JsonResult.createSuccess( departmentService.parentDept());
    }

    //查询单个
    @GetMapping("/findOne/{id}")
    public JsonResult findOne(@PathVariable("id") Long id) {
        departmentService.findOne(id);
        return JsonResult.createSuccess();
    }

    //新增或修改
    @PostMapping
    @ApiOperation(value="新增/修改用户", notes="描述")
    //新增与修改要添加跳转的 主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)
    public JsonResult save(@Valid @ApiParam(value = "新增/修改用户参数", required = true)@RequestBody Department department) {
        try {
            departmentService.saveOrUpdata(department);
            return JsonResult.createSuccess();
        } catch (RuntimeException e){
            e.printStackTrace();
            return JsonResult.createError(e.getMessage());
        } catch(Exception e) {
           e.printStackTrace();
            return JsonResult.createError("系统异常,请联系管理员");
        }

    }

    //删除
    @DeleteMapping("/{id}")
    public JsonResult deleteId(@PathVariable("id") Long id) {
        try {
            departmentService.deleteId(id);
            return JsonResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.createError("系统异常,请联系管理员");
        }
    }
    //批量删除
    @PostMapping("/deleteIds/{ids}")
    public JsonResult deleteIdS(@PathVariable("ids") Long[] ids) {
        try {
            departmentService.deleteAll(ids);
            return JsonResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.createError("系统异常,请联系管理员");
        }
    }


}
